<template>
  <div class="q-role">
    <el-button size="small" class="filter-item" style="margin-bottom: 20px;" type="primary" icon="el-icon-edit" @click="handleCreate">Add</el-button>
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column label="角色ID" prop="id" align="center" width="150" />
      <el-table-column label="角色名称" prop="role_name" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button v-if="row.id != 1" type="primary" size="mini" @click="handleUpdate(row)">Edit</el-button>
          <el-button v-if="row.id != 1" size="mini" type="danger" @click="handleRole(row, $index)">权限</el-button>
          <el-button v-if="row.id != 1" size="mini" type="danger" @click="handleDelete(row.id, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="RoleName" width="1012px" :visible.sync="dialogRoleVisible" element-loading-text="Loading">
      <template>
        <p style="text-align: center; margin: 0 0 20px">Index和Public控制器中的方法为共用方法,方法名中包含Public的方法,不参与权限</p>
        <div>
          <el-transfer
            v-model="RoleValue"
            :data="RoleData"
            :titles="['未分配权限', '已分配权限']"
            :button-texts="['到左边', '到右边']"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}'
            }"
            @change="handleRoleChange"
          />
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="temp.role_name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
  .el-transfer-panel{
    width: 350px;
    height: 500px;
  }
  .el-transfer-panel__list{
    height: 460px;
  }
</style>

<script>
  import { getData, postData } from '@/api/requestData'
  import { Message } from 'element-ui'

  export default {
    filters: {},

    data() {
      return {
        RoleData: [],
        RoleValue: [],
        RoleName: '',
        RoleId: '',
        list: [],
        listLoading: true,
        temp: {
          id: undefined,
          role_name: '',
        },
        dialogFormVisible: false,
        dialogRoleVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        rules: {
          role_name: [{ required: true, message: '角色名称必填', trigger: 'blur' }]
        },
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      /**
       * 用户列表
       */
      fetchData() {
        this.listLoading = true

        // 获取用户列表
        getData('user/role').then(response => {
          this.listLoading = false
          this.list = response.data
        }).catch(() => {
          this.listLoading = false
        })
      },

      resetTemp() {
        this.temp = {
          id: undefined,
          role_name: '',
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            postData('/user/role/create', this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            postData('/user/role/update', tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      /**
       * 删除角色
       */
      handleDelete(id, index) {
        this.$confirm('确认删除此角色?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonType: 'warning',
          cancelButtonType: 'text',
          type: 'warning'
        }).then(() => {
          // 确认处理逻辑
          postData('/user/role/delete', { 'id': id }).then(response => {
            this.list.splice(index, 1)
            Message({
              message: response.message,
              type: 'success',
              duration: 1000
            })
          }).catch(() => {
            //
          })
        }).catch(() => {
          // todo  取消处理逻辑  可不处理
        })
      },
      handleRole(row, index) {
        this.RoleData = []
        this.RoleValue = []
        this.RoleName = ''
        getData('/user/role/node/' + row['id']).then((response) => {
          this.dialogRoleVisible = true
          this.RoleName = row['role_name'] + ' 权限分配'
          this.RoleId = row['id']
          for (let i = 0; i < response.data.AllRoutes.length; i++) {
            this.RoleData.push({
              key: response.data.AllRoutes[i],
              label: `${response.data.AllRoutes[i]}`
            });
          }
          if (response.data.hasRoutes != null){
            for (let i = 0; i < response.data.hasRoutes.length; i++) {
              this.RoleValue.push(response.data.hasRoutes[i]);
            }
          }
        })
      },
      handleRoleChange(value, direction, movedKeys) {
        postData('/user/role/node/update', { 'id': this.RoleId, 'nodes': value.toString() }).then(response => {
          // todo
        }).catch(() => {})
      }
    }
  }
</script>

<style lang="scss" scoped>
.q-role {
  height: 100%;
  background-color: #FFFFFF;
  padding: 20px;
}
</style>
